import { defineStore } from 'pinia'
import { useMutation } from '@tanstack/vue-query'
import api from '../api'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
    accessToken: localStorage.getItem('access_token') || null,
    refreshToken: localStorage.getItem('refresh_token') || null,
    isAuthenticated: false
  }),
  
  getters: {
    getUser: (state) => state.user,
    getAccessToken: (state) => state.accessToken,
    getRefreshToken: (state) => state.refreshToken,
    getIsAuthenticated: (state) => state.isAuthenticated
  },
  
  actions: {
    setUser(user) {
      this.user = user
    },
    
    setTokens(accessToken, refreshToken) {
      this.accessToken = accessToken
      this.refreshToken = refreshToken
      if (accessToken && refreshToken) {
        localStorage.setItem('access_token', accessToken)
        localStorage.setItem('refresh_token', refreshToken)
        this.isAuthenticated = true
      } else {
        localStorage.removeItem('access_token')
        localStorage.removeItem('refresh_token')
        this.isAuthenticated = false
      }
    },
    
    // 登录的 useMutation 配置
    useLogin() {
      return useMutation({
        mutationFn: (credentials) => api.post('/auth/login', credentials),
        onSuccess: (result) => {
          if (result.data.code === 200) {
            // 假设后端返回包含 access_token 和 refresh_token 的对象
            const { access_token, refresh_token } = result.data.data
            this.setTokens(access_token, refresh_token)
          }
        },
        onError: (error) => {
          console.error('登录错误:', error)
        }
      })
    },
    
    async login(credentials) {
      try {
        const { mutateAsync } = this.useLogin()
        const response = await mutateAsync(credentials)
        if (response?.data?.code === 200) {
          return { success: true }
        } else {
          return { success: false, message: response?.data?.msg || '登录失败' }
        }
      } catch (error) {
        console.error('登录错误:', error)
        return { 
          success: false, 
          message: error.response?.status === 401 
            ? '用户名或密码错误' 
            : '登录失败，请检查用户名和密码' 
        }
      }
    },
    
    // 刷新token的 useMutation 配置
    useRefreshToken() {
      return useMutation({
        mutationFn: () => {
          return api.post('/auth/refresh', {
            refresh_token: this.refreshToken
          })
        },
        onSuccess: (result) => {
          if (result.data.code === 200) {
            // 更新access token
            const { access_token } = result.data.data
            this.accessToken = access_token
            localStorage.setItem('access_token', access_token)
          } else {
            // 刷新失败，需要重新登录
            this.logout()
          }
        },
        onError: (error) => {
          console.error('刷新token失败:', error)
          // 刷新失败，需要重新登录
          this.logout()
        }
      })
    },
    
    // 获取用户信息的 useQuery 配置
    useFetchUserInfo() {
      return useMutation({
        mutationFn: () => api.get('/auth/info'),
        onSuccess: (result) => {
          if (result.data.code === 200) {
            this.setUser(result.data.data)
          }
        },
        onError: (error) => {
          console.error('获取用户信息失败:', error)
          // 如果获取用户信息失败，清除认证状态
          this.logout()
        }
      })
    },
    
    async fetchUserInfo() {
      try {
        const { mutateAsync } = this.useFetchUserInfo()
        const response = await mutateAsync()
        if (response?.data?.code === 200) {
          return { success: true }
        } else {
          return { success: false, message: '获取用户信息失败' }
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 如果获取用户信息失败，清除认证状态
        this.logout()
        return { success: false, message: '获取用户信息失败' }
      }
    },
    
    logout() {
      this.setUser(null)
      this.setTokens(null, null)
    }
  }
})